/* Copyright 2009 Requirements Management System
 *   
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.model.commons;

import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import org.apache.commons.validator.GenericValidator;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

/**
 * 
 * @author Mario Gaitan
 *
 */
public class AuditInterceptor extends EmptyInterceptor {	
	private static AuditInterceptor instance = null;
	private String userName;
	private String hostName;
	
	public String getHostName() {
		if(hostName==null) {
		   try {
			   hostName = InetAddress.getLocalHost().getHostName();
		    } catch (UnknownHostException e) {/*IGNORE EXCEPTION*/}
		    if(GenericValidator.isBlankOrNull(hostName))
		    	hostName = "-unknown-";
		}
		return hostName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public static AuditInterceptor getInstance() {
		if(instance==null) 
			instance = new AuditInterceptor();
		return instance;
	}
	private AuditInterceptor() {
	}
	public String getUserName() {
		if(GenericValidator.isBlankOrNull(userName))
			userName = "remas";
		return userName;
	}
	@Override
	public boolean onFlushDirty(Object object, Serializable id, Object[] currentState,
			Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
		for(int i=0;i<=propertyNames.length-1;i++) {
			if(propertyNames[i].equalsIgnoreCase("updatedBy"))
				currentState[i] = getUserName();
			else
			if(propertyNames[i].equalsIgnoreCase("changeDate"))
				currentState[i] = new Date();
			
		}
		return true;
	}
	@Override
	public boolean onSave(Object object, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) throws CallbackException {
		for(int i=0;i<=propertyNames.length-1;i++) {
			if(propertyNames[i].equalsIgnoreCase("createdBy"))
				state[i] = getUserName();
			else
			if(propertyNames[i].equalsIgnoreCase("updatedBy"))
				state[i] = getUserName();
			else
			if(propertyNames[i].equalsIgnoreCase("creationDate"))
				state[i] = new Date();
			else
			if(propertyNames[i].equalsIgnoreCase("changeDate"))
				state[i] = new Date();
		}		
		return true;
	}

}
